package main

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"webhook-agents/config"
	"webhook-agents/webhooks"
)

// 精确的路由处理函数
func skywalkingHandler(w http.ResponseWriter, r *http.Request) {
	handler := webhooks.NewWebhookHandler()
	handler.HandleSkyWalkingAlert(w, r)
}

// 特殊处理kube-event，兼容kubeeventer的错误URL格式
func kubeEventHandler(w http.ResponseWriter, r *http.Request) {
	handler := webhooks.NewWebhookHandler()
	handler.HandleKubeEventAlert(w, r)
}

// 处理kubeeventer错误格式的专门函数
func kubeeventerErrorHandler(w http.ResponseWriter, r *http.Request) {
	// 检查端点是否启用
	if endpoint, ok := config.Global.Diting.Endpoints["kube_event"]; ok && !endpoint.Enabled {
		http.Error(w, "Kubernetes事件端点已禁用", http.StatusForbidden)
		return
	}

	// 检查是否已经处理过（通过添加一个标记）
	if r.Header.Get("X-Processed-By-Kubeeventer-Handler") == "true" {
		// 如果已经处理过，直接调用正常的处理器
		handler := webhooks.NewWebhookHandler()
		handler.HandleKubeEventAlert(w, r)
		return
	}

	// 修复URL格式：将第一个&替换为?
	originalPath := r.URL.Path
	fixedPath := strings.Replace(r.URL.Path, "&", "?", 1)
	log.Printf("🔧 修复kubeeventer错误URL格式: %s -> %s", originalPath, fixedPath)

	// 创建一个新的请求，使用修复后的URL
	newReq := r.Clone(r.Context())

	// 更新请求的URL路径和原始URL
	parts := strings.SplitN(fixedPath, "?", 2)
	if len(parts) == 2 {
		newReq.URL.Path = parts[0]
		newReq.URL.RawQuery = parts[1]
	} else {
		newReq.URL.Path = fixedPath
	}

	// 添加处理标记，防止循环
	newReq.Header.Set("X-Processed-By-Kubeeventer-Handler", "true")

	// 直接调用正确的处理器
	kubeEventHandler(w, newReq)
}

func falcoHandler(w http.ResponseWriter, r *http.Request) {
	handler := webhooks.NewWebhookHandler()
	handler.HandleFalcoAlert(w, r)
}

// disabledHandler 禁用端点的处理函数
func disabledHandler(endpointName string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, fmt.Sprintf("%s端点已禁用", endpointName), http.StatusForbidden)
	}
}

// healthCheckHandler 健康检查处理函数
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
	handler := webhooks.NewWebhookHandler()
	handler.HealthCheck(w, r)
}

func main() {
	// 加载配置
	if err := config.Load("agent-config.yaml"); err != nil {
		log.Fatalf("❌ 配置加载失败: %v", err)
	}

	// 注册路由 - 根据配置启用或禁用
	http.HandleFunc("/health", healthCheckHandler)

	// SkyWalking端点
	if endpoint, ok := config.Global.Diting.Endpoints["skywalking"]; ok && endpoint.Enabled {
		http.HandleFunc("/webhook/skywalking", skywalkingHandler)
		log.Printf("✅ 已启用SkyWalking端点: /webhook/skywalking")
	} else {
		http.HandleFunc("/webhook/skywalking", disabledHandler("SkyWalking"))
		log.Printf("❌ 已禁用SkyWalking端点: /webhook/skywalking")
	}

	// Kubernetes事件端点
	if endpoint, ok := config.Global.Diting.Endpoints["kube_event"]; ok && endpoint.Enabled {
		http.HandleFunc("/webhook/kube-event", kubeEventHandler)
		// 特别处理kubeeventer的错误格式URL
		http.HandleFunc("/webhook/kube-event&", kubeeventerErrorHandler)
		log.Printf("✅ 已启用Kubernetes事件端点: /webhook/kube-event")
	} else {
		http.HandleFunc("/webhook/kube-event", disabledHandler("Kubernetes事件"))
		http.HandleFunc("/webhook/kube-event&", disabledHandler("Kubernetes事件"))
		log.Printf("❌ 已禁用Kubernetes事件端点: /webhook/kube-event")
	}

	// Falco端点
	if endpoint, ok := config.Global.Diting.Endpoints["falco"]; ok && endpoint.Enabled {
		http.HandleFunc("/webhook/falco", falcoHandler)
		log.Printf("✅ 已启用Falco端点: /webhook/falco")
	} else {
		http.HandleFunc("/webhook/falco", disabledHandler("Falco"))
		log.Printf("❌ 已禁用Falco端点: /webhook/falco")
	}

	// 启动HTTP服务
	port := config.Global.Server.Port
	log.Printf("🚀 Webhook Agents服务启动中，监听端口 :%d", port)

	// 打印启用的端点信息
	log.Printf("📡 启用的webhook端点:")
	if endpoint, ok := config.Global.Diting.Endpoints["skywalking"]; ok && endpoint.Enabled {
		log.Printf("   - SkyWalking: http://localhost:%d/webhook/skywalking", port)
	}
	if endpoint, ok := config.Global.Diting.Endpoints["kube_event"]; ok && endpoint.Enabled {
		log.Printf("   - Kubernetes事件: http://localhost:%d/webhook/kube-event", port)
	}
	if endpoint, ok := config.Global.Diting.Endpoints["falco"]; ok && endpoint.Enabled {
		log.Printf("   - Falco: http://localhost:%d/webhook/falco", port)
	}

	log.Printf("✅ 服务已启动，等待告警webhook请求...")

	if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
		log.Fatalf("❌ 启动失败: %v", err)
	}
}
